﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Touch2Like.DAL;
using Touch2Like.Model;
using Touch2Like.SharedLibrary;
using System.Xml;

namespace Touch2Like.Web.Touch2Rate
{
    public partial class Survey : System.Web.UI.Page
    {
        string taguid = "";

        ReviewDAL review = new ReviewDAL();

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ExpiresAbsolute = DateTime.Now.AddDays(-1d);
            Response.Expires = -1500;
            Response.CacheControl = "no-cache";

            string browserguid = "";
            if (Request.Cookies["BrowserGUID"] != null && Request.Cookies["BrowserGUID"].Value != null)
                browserguid = Request.Cookies["BrowserGUID"].Value;
            else
            {
                browserguid = Guid.NewGuid().ToString();
                HttpCookie browserguidcookie = new HttpCookie("BrowserGUID", browserguid);
                browserguidcookie.Expires = DateTime.Now.AddDays(365);
                Response.SetCookie(browserguidcookie);
            }

            if (!string.IsNullOrEmpty(Request["taguid"]))
                taguid = Request["taguid"];

            if (!IsPostBack)
            {
                ViewState["BrowserGUID"] = browserguid;

                UserTagDAL tag = new UserTagDAL();
                UserTagInfo tagInfo = tag.GetUserTagByTagUID(taguid);

                if (tagInfo != null)
                {
                    UserDAL user = new UserDAL();
                    DataTable dtSetting = user.GetSettingByUserGUID(tagInfo.UserGUID);

                    if (dtSetting.Select("FlagName='Logo'").Length > 0)
                    {
                        img_logo.Src = dtSetting.Select("FlagName='Logo'")[0]["Value"].ToString();
                    }

                    QuestionDAL question = new QuestionDAL();
                    DataTable dtSet = question.GetByUserGUID(tagInfo.UserGUID);

                    if (dtSet.Rows.Count > 0)
                    {
                        int Number = 1;
                        string setid = dtSet.Rows[0]["QuestionSetID"].ToString();

                        ViewState["QuestionSetID"] = setid;

                        DataTable dtQuestion = question.GetBySetID(setid);
                        dtQuestion.DefaultView.Sort = "OrderNum ASC";
                        dtQuestion = dtQuestion.DefaultView.ToTable();
                        DataTable dt = new DataTable();
                        dt.Columns.Add("Question");
                        dt.Columns.Add("QuestionID");
                        dt.Columns.Add("QuestionItems");

                        foreach (DataRow drQuestion in dtQuestion.Rows)
                        {
                            DataRow dr = dt.NewRow();
                            dr["QuestionID"] = drQuestion["ListID"];
                            string q = drQuestion["Question"].ToString();
                            string items = "";
                            if (drQuestion["QuestionType"].ToString() == "YesNo" || drQuestion["QuestionType"].ToString() == "Comment" || drQuestion["QuestionType"].ToString() == "Rate")
                            {
                                dr["Question"] = q;
                                if (drQuestion["QuestionType"].ToString() == "YesNo")
                                {
                                    items = "<label class='radio'><input type='radio' name='rb" + dr["QuestionID"] + "' /><span></span>Yes</label><label class='radio'><input type='radio'  name='rb" + dr["QuestionID"] + "' /><span></span>No</label>";

                                    dr["QuestionItems"] = "<span class='rbitems' qid='" + drQuestion["ListID"] + "'><input name='answer" + drQuestion["ListID"] + "' type='hidden' />" + items + "</span>";
                                }
                                else if (drQuestion["QuestionType"].ToString() == "Comment")
                                {
                                    items = "<label><textarea rows='3'></textarea></label>";

                                    dr["QuestionItems"] = "<span class='tbcomment' qid='" + drQuestion["ListID"] + "'><input name='answer" + drQuestion["ListID"] + "' type='hidden' />" + items + "</span>";
                                }
                                else
                                {
                                    items = "<label><input type='text' class='rating rating5' /></label>";
                                    dr["QuestionItems"] = "<span class='tbrate' qid='" + drQuestion["ListID"] + "'><input name='answer" + drQuestion["ListID"] + "' type='hidden' />" + items + "</span>";
                                }
                            }
                            else if (drQuestion["QuestionType"].ToString() == "MultiCheck")
                            {
                                XmlDocument doc = new XmlDocument();
                                doc.LoadXml(q);

                                dr["Question"] = doc.SelectSingleNode("/Q/Question").InnerText;
                                foreach (XmlNode node in doc.SelectNodes("/Q/Item"))
                                {
                                    items += "<label class='checkbox'><input type='checkbox' /><span></span>" + node.InnerText + "</label>";
                                }

                                dr["QuestionItems"] = "<span class='cbitems' qid='" + drQuestion["ListID"] + "'><input name='answer" + drQuestion["ListID"] + "' type='hidden' />" + items + "</span>";
                            }
                            else if (drQuestion["QuestionType"].ToString() == "SingleCheck")
                            {
                                XmlDocument doc = new XmlDocument();
                                doc.LoadXml(q);

                                dr["Question"] = doc.SelectSingleNode("/Q/Question").InnerText;
                                foreach (XmlNode node in doc.SelectNodes("/Q/Item"))
                                {
                                    items += "<label class='radio'><input type='radio' name='rb" + dr["QuestionID"] + "' /><span></span>" + node.InnerText + "</label>";
                                }

                                dr["QuestionItems"] = "<span class='rbitems' qid='" + drQuestion["ListID"] + "'><input name='answer" + drQuestion["ListID"] + "' type='hidden' />" + items + "</span>";
                            }

                            dr["Question"] = Number + ". " + dr["Question"];
                            dt.Rows.Add(dr);
                            Number += 1;
                        }

                        Repeater_Question.DataSource = dt;
                        Repeater_Question.DataBind();
                    }

                    DataTable dtBrowser = review.GetByBrowserGUID(browserguid);
                    dtBrowser.DefaultView.RowFilter = "TagUID='" + taguid + "'";
                    dtBrowser.DefaultView.Sort = "createdate desc";
                    dtBrowser = dtBrowser.DefaultView.ToTable();
                    if (dtBrowser.Rows.Count > 0)
                    {
                        if (Convert.ToDateTime(dtBrowser.Rows[0]["CreateDate"]).AddSeconds(15) > DateTime.Now)
                            btn_Submit.Enabled = false;
                    }
                }
            }
        }

        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            ReviewInfo reviewInfo = new ReviewInfo();
            reviewInfo.BrowserGUID = ViewState["BrowserGUID"].ToString();
            reviewInfo.TagUID = taguid;

            UserTagDAL tag = new UserTagDAL();
            UserTagInfo tagInfo = tag.GetUserTagByTagUID(taguid);

            if (tagInfo != null)
            {
                reviewInfo.UserGUID = tagInfo.UserGUID;
                reviewInfo.ActivityID = Convert.ToInt32(Request["activityid"]);
                reviewInfo.TableNumber = "";
                reviewInfo.CreateDate = DateTime.Now;

                int reviewid = review.Add(reviewInfo);
                string setid = ViewState["QuestionSetID"].ToString();

                QuestionDAL question = new QuestionDAL();
                DataTable dtQuestion = question.GetBySetID(setid);

                AnswerDAL answer = new AnswerDAL();
                AnswerInfo answerInfo = new AnswerInfo();

                foreach (DataRow drQuestion in dtQuestion.Rows)
                {
                    int qid = Convert.ToInt32(drQuestion["ListID"]);
                    answerInfo.QuestionID = qid;
                    answerInfo.ReviewID = reviewid;
                    answerInfo.UserGUID = reviewInfo.UserGUID;
                    answerInfo.Answer = Request["answer" + qid];
                    answerInfo.CreateDate = reviewInfo.CreateDate;

                    answer.Add(answerInfo);
                }

                UserDAL user = new UserDAL();
                DataTable dtSetting = user.GetSettingByUserGUID(reviewInfo.UserGUID);

                if (dtSetting.Select("FlagName='URL'").Length > 0)
                    Response.Redirect(dtSetting.Select("FlagName='URL'")[0]["Value"].ToString(), true);
                else
                    Response.Redirect("/Touch2Rate/Result.aspx?reviewid=" + Server.UrlEncode(Utility.Encryption.Encrypt(reviewid.ToString())));
            }
        }
    }
}